//
//  WCNetworkAccessManager.m
//  WC
//
//  Created by 杨鑫 on 15/4/28.
//  Copyright (c) 2015年 智康. All rights reserved.
//

#import "WCNetworkAccessManager.h"
#import "WCPopupLayerManager.h"
#import "Macros.h"
#import "WCDefaultManager.h"
#import "WCNLoginVC.h"
//#import "ChatManager.h"
#import "WCNTabBarVC.h"
#import "WCNNavigationController.h"
#import "JCAlertView.h"
#import "Constants.h"
//
@import CoreTelephony;

@interface WCNetworkAccessManager ()

@property (strong, nonatomic) AFHTTPSessionManager *httpRequestOperationManager;
@property (strong, nonatomic) NSString *payUrl;

//退出后清空
@property (strong, nonatomic) NSMutableDictionary *urlTime;

@end

@implementation WCNetworkAccessManager

+ (instancetype)sharedMg
{
    static WCNetworkAccessManager *sharedMg = nil;
    //block
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMg = [[WCNetworkAccessManager alloc] initPrivate];
    });
    return sharedMg;
}

// No one should call init
- (instancetype)init
{
    @throw [NSException exceptionWithName:@"Singleton"
                                   reason:@"Use +[WCNetworkAccessManager sharedMg]"
                                 userInfo:nil];
    return nil;
}

- (NSString *)getWexinAccessTokenApi{

     NSDictionary *configs =[NSDictionary dictionaryWithContentsOfFile:[self getConfigFilePath]];
    NSString *model = nil;
#if DEBUG
    model = configs[@"MODEL"];
    
#else
    model =@"ali";
    
#endif
    NSDictionary *dict =configs[@"WexinAccessTotaken"];
    ;

    return  [NSString stringWithFormat:@"%@/care-wechat/wechat/getToken",dict[model]];
}

- (instancetype)initPrivate
{
    self = [super init];
    if (self) {
        NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:[self getConfigFilePath]];
        NSString *model = nil;
#if DEBUG
        model = configs[@"MODEL"];
       
       
        
#else
        model =@"ali";
        
#endif
        NSDictionary *urls = configs[@"URLS"];
        NSDictionary *payUrls = configs[@"PAYS"];
        _bathURL = urls[model];
        _payUrl = payUrls[model];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 10;
        manager.securityPolicy.allowInvalidCertificates = [configs[@"HTTPS"] boolValue];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil];
         self.httpRequestOperationManager = manager;
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
        _urlTime = [[NSMutableDictionary alloc] init];
        
        // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        // 检测网络连接的单例,网络变化时的回调方法
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if (status == AFNetworkReachabilityStatusUnknown) {
                self.netStatus = NetworkStatusUnknow;
            } else if (status == AFNetworkReachabilityStatusNotReachable) {
                self.netStatus = NetworkStatusNO;
            } else if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
                CTTelephonyNetworkInfo *networkStatus = [[CTTelephonyNetworkInfo alloc]init];
                NSString *currentStatus  = networkStatus.currentRadioAccessTechnology;
                if (currentStatus == CTRadioAccessTechnologyLTE){
                    self.netStatus = NetworkStatus4G;
                } else if (currentStatus == CTRadioAccessTechnologyeHRPD) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMAEVDORevB) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMAEVDORevA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMAEVDORev0) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyCDMA1x) {
                    self.netStatus = NetworkStatus2G;
                } else if (currentStatus == CTRadioAccessTechnologyHSUPA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyHSDPA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyWCDMA) {
                    self.netStatus = NetworkStatus3G;
                } else if (currentStatus == CTRadioAccessTechnologyEdge) {
                    self.netStatus = NetworkStatus2G;
                } else if (currentStatus == CTRadioAccessTechnologyGPRS) {
                    self.netStatus = NetworkStatus2G;
                }
            } else if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
                self.netStatus = NetworkStatusWIFI;
            } else {
                self.netStatus = NetworkStatusUnknow;
            }
        }];
    }
    return self;
}
- (void)setNetStatus:(NetworkStatus)netStatus{
    _netStatus = netStatus;
}
#pragma mark - record time

- (NSTimeInterval)timeSinceLastUrl:(NSString *)url
{
    NSDate *current = [NSDate date];
    NSDate *date = _urlTime[url];
    if (date) {
        return [current timeIntervalSinceDate:date];
    } else {
        return [current timeIntervalSince1970];
    }
}

- (void)recordTime:(NSString *)url
{
    [_urlTime setValue:[NSDate date] forKey:url];
}

- (void)resetTimeDic
{
    [_urlTime removeAllObjects];
}


- (NSString *)getBaseUrl{
    return _bathURL;
}
- (NSString *)getSessionKey
{
     Account *accout =[[WCDefaultManager shareMg] account];
    return accout.sessionKey;
}
#pragma mark - http

- (NSURLSessionDataTask *)GET:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)(id responseObject))success
                        failure:(void (^)(NSString *msg))failure
                       netError:(void (^)(id error))netError
                         always:(void (^)(void)) always
{
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@", _bathURL, URLString];
   
    
    urlStr = [NSString stringWithFormat:@"%@/%@?sessionKey=%@", _bathURL, URLString,[self getSessionKey]];
    
 
    NSURLSessionDataTask *sessionDataTask = [self.httpRequestOperationManager GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        NSLog(@"%@",result);
        BOOL isSuccess = [result[@"success"] boolValue];
        if (isSuccess) {
            success(result);
            [self recordTime:URLString];
        } else {
           
                id error =result[@"errMsg"];
                NSString *msgStr;
                if ([error isKindOfClass:[NSDictionary class]]) {
                    msgStr =error[@"errorMessage"];
                    NSString *code=error[@"errorCode"];
                    [self handleWithSessionKeyErrorWithCode:code successBlock:^{
                        NSString *lastUrl =[NSString stringWithFormat:@"%@/%@?sessionKey=%@", _bathURL, URLString,[self getSessionKey]];
                        
                    [self.httpRequestOperationManager POST:lastUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            if (always) {
                                always();
                            }
                            
                            //上次层的sucess
                            if (success) {
                                success((NSDictionary *)responseObject);
                                [self recordTime:URLString];
                            }
                            
                            
                            
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            if (always) {
                                always();
                            }
                            [self showNetError:task with:error];
                            
                            if (netError) {
                                netError(nil);
                            }
                            if (always) {
                                always();
                            }
                            
                        }];
                        
                    }];
                    return;                    return;
                    
                }else{
                    msgStr =error;
                }
                
                
                if (failure) {
                    failure(msgStr);
                } else {
                    // [[WCPopupLayerManager shareMg] showTextOnly:msgStr withView:[UIApplication sharedApplication].keyWindow];
                    WSJSHOW(msgStr);
                }
            }
    
        
        always?always():nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showNetError:task with:error];
        
        netError?netError(nil):nil;
        always?always():nil;

    }];
    
    return sessionDataTask;
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)(id responseObject))success
                         failure:(void (^)(NSString *msg))failure
                        netError:(void (^)(id error))netError
                          always:(void (^)(void)) always
{
    
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@", _bathURL, URLString];
    
    urlStr = [NSString stringWithFormat:@"%@/%@?sessionKey=%@", _bathURL, URLString,[self getSessionKey]];

    NSLog(@"%@",urlStr);
    NSURLSessionDataTask *task = [self.httpRequestOperationManager POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = responseObject;
        BOOL isSuccess = [result[@"success"] boolValue];
        if (isSuccess) {
            success(result);
            [self recordTime:URLString];
        } else {
            NSDictionary *result = responseObject;
            BOOL isSuccess = [result[@"success"] boolValue];
            if (isSuccess) {
                success(result);
                [self recordTime:URLString];
            } else {
                id error =result[@"errMsg"];
                NSString *msgStr;
                if ([error isKindOfClass:[NSDictionary class]]) {
                    msgStr =error[@"errorMessage"];
                    NSString *code=error[@"errorCode"];
                    [self handleWithSessionKeyErrorWithCode:code successBlock:^{
                        NSString *lastUrl =[NSString stringWithFormat:@"%@/%@?sessionKey=%@", _bathURL, URLString,[self getSessionKey]];
                        
                        
                        [self.httpRequestOperationManager POST:lastUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            if (always) {
                                always();
                            }
                            
                            //上次层的sucess
                            if (success) {
                                success((NSDictionary *)responseObject);
                                [self recordTime:URLString];
                            }
                            
                            
                            
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            if (always) {
                                always();
                            }
                            [self showNetError:task with:error];
                            
                            if (netError) {
                                netError(nil);
                            }
                            if (always) {
                                always();
                            }
                            
                        }];
                        
                    }];
                    return;
                }else{
                    msgStr =error;
                }
                
                
                if (failure) {
                    failure(msgStr);
                } else {
                    [[WCPopupLayerManager shareMg] showTextOnly:msgStr withView:[UIApplication sharedApplication].keyWindow];
                }
            }
        }
        
        
        always?always():nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showNetError:task with:error];
        if (netError) {
            netError(error.localizedDescription);
        }
        
        always?always():nil;
    }];
    
    return task;
}



- (void)handleWithSessionKeyErrorWithCode:(NSString *)code successBlock:(void(^)(void))successBlock
{
    //sessionKey 过期 静默登陆
    if ([code integerValue]==9002) {
      //自动登陆获得sessionKey
         NSDictionary *params =[[WCDefaultManager shareMg] loginNameAndMd5Pwd];
        //早期版本没有保存密码 ,升级后数据库中有用户信息,默认不需登陆   但启动 因为sessionKey的增加,需要 获取账号和密码 来重新默认登陆
        defineWeakSelf;
       
        NSLog(@"重新登陆参数--------%@",params);
        
        CoreSVPLoading(@"重新登录中...", NO);
        [[WCNetworkAccessManager sharedMg] POST:kLoginUrl
                                     parameters:params
                                        success:^(NSDictionary *responseData){
                                            NSDictionary *dictData =responseData[@"data"];
                                            
                                            NSDictionary *userData =dictData[@"sessionUser"];
                                            
                                            NSMutableDictionary *dataDict =[NSMutableDictionary new];
                                            dataDict[@"sessionKey"] =dictData[@"sessionKey"];
                                            [dataDict addEntriesFromDictionary:userData[@"value"]];

                                            dataDict[@"pwd"] =params[@"password"];

                                            [[WCDefaultManager shareMg] login:dataDict];
                                            if (successBlock) {
                                                successBlock();
                                            }
                                            
                                              [[NSNotificationCenter defaultCenter] postNotificationName:UserLoginNotification object:nil userInfo:nil];
                                            //环信登陆在 tbc
                                        } failure:^(NSString *err){
                                           [weakSelf loginFail];
                                            
                                            
                                        } netError:nil always:^(){
                                            [CoreSVP dismiss];
                                        }];
         

    }else if([code integerValue]==9003){
        [self loginFail];
    }
    
}

- (void)loginFail{
    
    
   

    
    [[WCDefaultManager shareMg] logout];
    //退出环信
    //        [[ChatManager sharedChatManager] LogoffHuanxin];
    
    
    WCNLoginVC *loginVC = [[WCNLoginVC alloc] init];
    WCNNavigationController * nav =(WCNNavigationController *)[[UIApplication sharedApplication].delegate window].rootViewController;
    [nav setViewControllers:@[loginVC] animated:NO];


}


#pragma mark - Private

- (void)showNetError:(NSURLSessionDataTask *)task with:(NSError *)error
{
    NSString *title;
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)task.response;
    NSInteger code = httpResponse.statusCode;
    if (code == 0) {
        NSInteger appleCode = error.code;
        if (appleCode == -1001) {
            title = @"连接超时";
        } else if (appleCode == -1004) {
            title = @"无法连接网络";
        }
    } else if (code == 400) {
        title = @"请求参数错误";
    } else if (code == 404) {
        title = @"找不到资源";
    } else if (code == 500) {
        title = @"服务器错误";
    }
    
    [[WCPopupLayerManager shareMg] showTextOnly:title withView:[UIApplication sharedApplication].keyWindow];
}

#pragma mark - path

- (NSString *)getConfigFilePath
{
    return [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
}

@end
